package ngamejava2;

import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import javax.xml.xpath.XPathExpressionException;
import org.w3c.dom.Node;

public class PlaneManager extends GameObjectContainer<GameObjectContainer, GamePlane>
{
	private Rectangle2D.Float camera;
	private Rectangle2D.Float viewport;

	public PlaneManager()
	{
		this(1, 1);
	}

	public PlaneManager(int width, int height)
	{
		super();
		this.getBounds().width = width;
		this.getBounds().height = height;
		camera = new Rectangle2D.Float(0, 0, width, height);
		viewport = new Rectangle2D.Float(0, 0, width, height);
	}

	public void centerCameraAt(GameObject actor)
	{
		camera.x = actor.getBounds().x + (actor.getBounds().width / 2) - (camera.width / 2);
		camera.y = actor.getBounds().y + (actor.getBounds().height / 2) - (camera.height / 2);
		if (camera.x < 0)
		{
			camera.x = 0;
		}
		if (camera.y < 0)
		{
			camera.y = 0;
		}
		if (camera.x + camera.width > getBounds().width)
		{
			camera.x = getBounds().width - camera.width;
		}
		if (camera.y + camera.height > getBounds().height)
		{
			camera.y = getBounds().height - camera.height;
		}
	}

	public Rectangle2D.Float getCamera()
	{
		return camera;
	}

	public Rectangle2D.Float getViewport()
	{
		return viewport;
	}

	@Override
	public void load()
	{
		resetIterator();
		while (iteratorHasNext())
		{
			getCurrentObject().load();
		}
	}

	@Override
	public void unload()
	{
		resetIterator();
		while (iteratorHasNext())
		{
			getCurrentObject().unload();
		}
	}

	@Override
	public void update(long currentTick)
	{
		resetIterator();
		while (iteratorHasNext())
		{
			getCurrentObject().update(currentTick);
		}
	}

	@Override
	public void render(Graphics2D g, long currentFrame)
	{
		Graphics2D gg = (Graphics2D) g.create();
		resetIterator();
		while (iteratorHasNext())
		{
			getCurrentObject().render(gg, currentFrame);
		}
	}

	@Override
	public void write(GameWriter gw) throws IOException
	{
		super.write(gw);
		gw.write("camera", getCamera());
		gw.write("viewport", getViewport());
	}

	@Override
	public void read(GameReader gr, Node objectNode) throws XPathExpressionException
	{
		super.read(gr, objectNode);
		camera = gr.readRectangle2D(objectNode, "rectangle[@name='camera']");
		viewport = gr.readRectangle2D(objectNode, "rectangle[@name='viewport']");
	}
}